/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gestionnaire;

import java.util.Collection;
import modeles.categorie;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author elo
 */
@Stateless
public class gestionnaireCategorie {
    
    @PersistenceContext
    private EntityManager em;

    public void creerCategories() {
        if(countCategories() == 0){
            creeCategorie("Jeux PS3");
            creeCategorie("Jeux Xbox 360");
            creeCategorie("Jeux Wii");
            creeCategorie("Jeux PC");
            creeCategorie("Jeux 3DS");
            creeCategorie("Jeux DS");
            creeCategorie("Jeux PSP");
            creeCategorie("Jeux Mac");
        }
    }

    public categorie creeCategorie(String nom) {
        categorie c = new categorie(nom);
        em.persist(c);
        return c;
    }

    public categorie getCategorieByName(String name){
        Query q = em.createQuery("select c from categorie c where c.libelle like :nom");
        q.setParameter("nom", name);
        Collection<Object> result = q.getResultList();
        if(result.size() == 0)
            return null;
        else
            return (categorie)result.toArray()[0];
    }

    public String getNomCategorieById(int id){
        Query q = em.createQuery("select c.libelle from categorie c where c.id = :id");
        q.setParameter("id", id);
        Collection<Object> result = q.getResultList();
        if(result.size() == 0)
            return null;
        else
            return result.toArray()[0].toString();
    }

    public Collection<categorie> getAllCategories() {
        // Exécution d'une requête équivalente à un select *
        Query q = em.createQuery("select c from categorie c order by c.libelle asc");
        return q.getResultList();
    }

    public int countCategories() {
        Query q = em.createQuery("select count(c) from categorie c");
        int nb = Integer.parseInt(q.getSingleResult().toString());
        return nb;

    }
}
